<?php

namespace App\Services;

use App\Models\Order;
use App\Models\OrderLease;

class AlipayMiniOrderService extends AlipayBaseService
{

    //申请待处理	PENDING
    //审批中	APPROVAL
    //提现成功	WITHDRAWAL_S
    //提现失败	WITHDRAWAL_F
    //已出账	BILLED
    //待还款	PAY_WAITING
    //还款失败	PAYMENT_F
    //已逾期	OVERDUE
    //已销户	CANCELLED
    //还款成功	PAYMENT_S
    //审批通过	AUDIT_PASS
    //审批失败	APPROVAL_F
    //已还清	PAID_OFF
    //已结清	FINISH
    const CONSUMER_FINANCE = [
        1 =>'APPROVAL_F',
        3 =>'AUDIT_PASS',
        4 =>'PENDING',
        30 =>'PAY_WAITING',
        38 =>'OVERDUE',
        39 =>'OVERDUE',
        11 =>'PAYMENT_S',
        44 =>'PAID_OFF',
        60 =>'FINISH',
    ];
    //创单成功	CREATE
    //待支付	WAIT_PAY
    //已关闭	CLOSED
    //退款中	REFUNDING
    //已退款	REFUNDED
    //已完成	FINISHED
    //支付完成	PAID
    //已发货	IN_DELIVERY
    //部分退款	REFUND_PART
    //部分退货	RETURN_PART
    //待发货	TO_SEND_GOODS
    //部分发货	PARTIAL_DELIVERY
    //已签收	SIGNED
    const ALIPAY_KX_SHOPPING_STATUS = [
        4 => 'CREATE',
        3 => 'WAIT_PAY',
        1 => 'CLOSED',
        16 => 'REFUNDED',
        60 => 'FINISHED',
        8 => 'PAID',
        20 => 'IN_DELIVERY',
        10 => 'TO_SEND_GOODS',
        30 => 'SIGNED',
    ];



     public static function createMiniOrder($order_id){

         $order = Order::from('sp_order_2 as o')->where('o.id', $order_id)
             ->leftjoin('sp_shop_user_2 as u', 'u.member_id', 'o.seller_id')
             ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
             ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
             ->leftjoin('sp_order_return_2 as or', 'o.id', 'or.order_id')
             ->select(
                 'o.id', 'o.mini_id', 'o.uid', 'o.status', 'o.rent_total', 'o.month_total', 'o.foregift', 'o.seller_id', 'o.trade_no', 'o.realname', 'o.mobile as user_mobile', 'o.flow_id', 'o.amount', 'o.other_order_id', 'o.other_user_id', 'o.form_id', 'o.create_time', 'o.payer_user_id', 'o.begin_time', 'o.end_time', 'o.pay_type', 'o.order_from', 'o.is_skip', 'o.financing_type', 'o.is_renewal', 'o.parent_order_no', 'o.pact_url_2', 'o.pact_url_3'
                 , 'og.goods_title', 'og.lease_price', 'og.lease_set', 'og.goods_id', 'og.setmeal_id', 'og.spec_id', 'og.lease_time', 'og.start_date', 'og.imgurl', 'og.setmeal_foregift'
                 , 'm.cert_no', 'm.user_id', 'm.cert_name', 'm.cert_no', 'm.mobile', 'm.esign_user_id', 'm.esign_seal_id'
                 , 'u.shopname', 'or.logistics_no', 'u.is_guarantee', 'o.payment', 'u.guarantee_amount', 'u.guarantee_minage', 'u.guarantee_maxage', 'u.mechanism'
             )
             ->first();
         $order = $order ? $order->toArray() : [];
         if (!$order['uid']) {
             return;
         }
         if (!self::ALIPAY_KX_SHOPPING_STATUS[$order['status']]) {
             return;
         }

         $miniId = $order['mini_id'];

         $data = [
             "out_order_id" => $order['trade_no'],
             'title' => $order['goods_title'],
             "source_id" => $order['source_id'],
             "merchant_biz_type" => 'STANDARD_RENT',
             "path" => '/pages/index/index?orderId=10190608609185',
             "order_detail" => [
                 [
                     'item_infos' => [['goods_name' => $order['goods_title'],
                         'item_cnt' => 1,
                         'sale_price' => $order['setmeal_foregift'],
                         'out_item_id' => $order['goods_id'],
                         'sale_real_price' => $order['setmeal_foregift'],
                         'item_installment_info' => ['period_num' => $order['month_total'],
                             'period_price' => bcdiv($order['setmeal_foregift'], $order['month_total'], 2)],
                     ]],
                     'title' => $order['goods_title'],
                     'price_info' => ['order_price' => $order['setmeal_foregift']],
                 ]
             ],//商品信息列表，详情可查看下文：商品信息列表。
             "seller_id" => '2088541530986955',
             "pay_amount" => $order['payment'],
         ];
         $request = new \AlipayOpenMiniOrderCreateRequest();
         $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest($miniId)->execute($request);
         self::requestLog('交易组件业务单创建', $data, $result);
     }

     //查询订单
     public static function queryMiniOrder($order){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id']
         ];
         $request = new \AlipayOpenMiniOrderQueryRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('查询订单接口', $data, $result);
     }


     /**
      * 履约推进过程中，更新履约变更状态
      * @param $order
      * @return void
      * @throws \Exception
      */
     public static function deliveryModify($order,$status){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id'],
             'status'=>$status
         ];
         $request = new \AlipayOpenMiniOrderDeliveryModifyRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('查询订单接口', $data, $result);
     }

     /**
      * 订单发货
      * @param $order
      * @return void
      * @throws \Exception
      */
     public static function deliverySend($order){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id'],
             'ship_done_time'=>date('Y-m-d H:i:s'),
             'delivery_list'=>['delivery_id'=>'SF','waybill_id'=>$order['delivery_no'],'item_infos'=>[
                 [
                 'goods_name'=>$order['goods_title'],
                 'item_cnt'=>1,
                 'out_sku_id'=>$order['goods_id']
                 ],
             ]]
         ];
         $request = new \AlipayOpenMiniOrderDeliverySendRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('查询订单接口', $data, $result);
     }


     /**
      * 订单确认收货
      * @param $order
      * @return void
      * @throws \Exception
      */
     public static function deliveryReceive($order){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id'],
         ];
         $request = new \AlipayOpenMiniOrderDeliveryReceiveRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('订单确认收货', $data, $result);
     }

     /**
      * 订单分期
      * @param $order
      * @return void
      * @throws \Exception
      */
     public static function installmentCreate($order){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id'],
         ];
         $request = new \AlipayOpenMiniOrderInstallmentCreateRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('订单确认收货', $data, $result);
     }

     /**
      * 订单关闭
      * @param $order
      * @return void
      * @throws \Exception
      */
     public static function installmentClose($order){
         $data = [
             "out_order_id" => $order['trade_no'],
             'order_id'=>$order['mini_order_id'],
             'user_id'=>$order['user_id'],
         ];
         $request = new \AlipayOpenMiniOrderCloseRequest();
         $request->setBizContent(json_encode($data,JSON_UNESCAPED_UNICODE));
         $result = self::aliPayXxzRequest()->execute($request);
         self::requestLog('订单确认收货', $data, $result);
     }


}
